//
//  NDNetworkReachability.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/24.
//

import Alamofire

class NDNetworkReachability {
    static let shared = NDNetworkReachability()
    
    private let reachabilityManager = NetworkReachabilityManager(host: "www.apple.com")
    private(set) var isNetworkReachable: Bool = false

    private init() {
        setupReachability()
    }
    
    private func setupReachability() {
        reachabilityManager?.startListening { [weak self] status in
            guard let self = self else { return }
            self.isNetworkReachable = status != .notReachable
            switch status {
            case .reachable(_):
                loadEnvironment()
            default:
                break
            }
        }
    }
    
    func stopListening() {
        reachabilityManager?.stopListening()
    }
    
    func loadEnvironment() {
        guard NDUserDefaults.shared.retrieveText(for: NDRegionCodeKey) == nil else {
            return
        }
        NDRequestManager.requestEnvironment { appEnvironment, message, error in
            if error == nil {
                if let countryId = appEnvironment?.governmentic {
                    NDUserDefaults.shared.saveText(countryId, for: NDRegionCodeKey)
                }
            }
        }
    }
}


